package com.drd.dt.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.drd.dt.back.dto.JGPushDTO;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;

/**
 * Created by 86514 on 2019/6/21.
 */
public class JgPushUtil {
    private static final Logger log = LoggerFactory.getLogger(JgPushUtil.class);
    private static String pushUrl = "https://api.jpush.cn/v3/push";
    private static boolean apns_production = true; //ios  true生产环境，false为开发环境
    private static int time_to_live = 86400;


    /**
     * 消息推送(精确推送)
     * @return
     */
    public static void pushMsg(String alert, JGPushDTO push, String appKey, String masterSecret, String registration_id) throws Exception{

        try {
            String result = push(pushUrl, registration_id, alert, appKey, masterSecret, apns_production, time_to_live, push);
            JSONObject resData = JSON.parseObject(result);
            if(resData.containsKey("error")){
                log.info("针对极光注册ID为【" + registration_id + "】的信息推送失败！");
                JSONObject error = JSON.parseObject(resData.getString("error"));
                log.info("错误信息为：" + error.get("message").toString());
            }else {
                log.info("针对极光注册ID为【" + registration_id + "】的信息推送成功！");
            }
        }catch(Exception e){
            log.error("针对极光注册ID为【" + registration_id + "】的信息推送失败！",e);
        }
    }


    /**
     * 组装极光推送专用json串
     *
     * @param registration_id
     * @param alert
     * @return json
     */
    public static JSONObject generateJson(String registration_id, String alert, boolean apns_production, int time_to_live, JGPushDTO push) {
        JSONObject json = new JSONObject();
        JSONArray platform = new JSONArray();//平台
        platform.add("android");
        platform.add("ios");

        JSONObject audience = new JSONObject();//推送目标
        JSONArray registrationId = new JSONArray();
        registrationId.add(registration_id);
        audience.put("registration_id", registrationId);

        JSONObject notification = new JSONObject();//通知内容
        JSONObject android = new JSONObject();//android通知内容
        android.put("alert", alert);
        android.put("builder_id", 1);
        JSONObject android_extras = new JSONObject();//android额外参数
        android_extras.put("data", push);
        android_extras.put("choose", "push");
        android.put("extras", android_extras);

        JSONObject ios = new JSONObject();//ios通知内容
        ios.put("alert", alert);
        ios.put("sound", "default");
        ios.put("badge", "+1");
        JSONObject ios_extras = new JSONObject();//ios额外参数
        ios_extras.put("jump_action", push.getJump_action());
        ios_extras.put("is_login", push.getIs_login());
        ios_extras.put("choose", "push");
        ios.put("extras", ios_extras);

        notification.put("android", android);
        notification.put("ios", ios);

        JSONObject options = new JSONObject();//设置参数
        options.put("time_to_live", Integer.valueOf(time_to_live));
        options.put("apns_production", apns_production);

        json.put("platform", platform);
        json.put("audience", audience);
        json.put("notification", notification);
        json.put("options", options);
        return json;
    }

    /**
     * 推送方法-调用极光API
     *
     * @param reqUrl
     * @param registration_id
     * @param alert
     * @return result
     */
    public static String push(String reqUrl, String registration_id, String alert, String appKey, String masterSecret, boolean apns_production, int time_to_live, JGPushDTO push) {
        String base64_auth_string = JgPushUtil.encryptBASE64(appKey + ":" + masterSecret);
        String authorization = "Basic " + base64_auth_string;
        return JgPushUtil.sendPostRequest(reqUrl, generateJson(registration_id, alert, apns_production, time_to_live, push).toString(), "UTF-8", authorization);
    }


    /**
     * 发送Post请求（json格式）
     * @param reqURL
     * @param data
     * @param encodeCharset
     * @param authorization
     * @return result
     */
    @SuppressWarnings({ "resource" })
    public static String sendPostRequest(String reqURL, String data, String encodeCharset,String authorization){
        HttpPost httpPost = new HttpPost(reqURL);
        HttpClient client = new DefaultHttpClient();
        HttpResponse response = null;
        String result = "";
        try {
            StringEntity entity = new StringEntity(data, encodeCharset);
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            httpPost.setHeader("Authorization",authorization.trim());
            response = client.execute(httpPost);
            result = EntityUtils.toString(response.getEntity(), encodeCharset);
        } catch (Exception e) {
            log.error("请求通信[" + reqURL + "]时偶遇异常,堆栈轨迹如下", e);
        }finally{
            client.getConnectionManager().shutdown();
        }
        return result;
    }

    /**
     * BASE64加密工具
     * */
    public static String encryptBASE64(String str) {
        byte[] key = str.getBytes();
        BASE64Encoder base64Encoder = new BASE64Encoder();
        String strs = base64Encoder.encodeBuffer(key);
        return strs;
    }
}
